#include<iostream>

#include<stdio.h>

#include <pthread.h>

#include<string>

#include<unistd.h>

#include<vector>

using namespace std;

int num = 0;

pthread_mutex_t MT = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t CD = PTHREAD_COND_INITIALIZER;

pthread_mutex_t m_mt = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t m_cd = PTHREAD_COND_INITIALIZER;

struct task
{
    string _name;
    pthread_t _PT;
};

void* my_pthread(void* arg)
{
    task* x = static_cast<task*>(arg);
    string str = x->_name;
    while(1)
    {
        pthread_mutex_lock(&MT);
        pthread_cond_wait(&m_cd, &MT);
        while(num<= 0)
        {
            pthread_cond_wait(&CD, &MT);
        }
        
        cout << str << "抢到了一张票：" << num-- << endl;
        // if(num <= 0) pthread_cond_broadcast(&m_cd);
        // usleep(100000);
        pthread_mutex_unlock(&MT);
        if(num <= 0) pthread_cond_broadcast(&m_cd);
        // usleep(100000); // 睡眠触发线程切换
    }
    return nullptr;
}

void* mysign(void* arg)
{
    while(1)
    {
        pthread_cond_signal(&m_cd);
        usleep(100);
    }
    return nullptr;
}

int main()
{
    vector<task*> arr;
    for(int i = 0; i < 10; ++i)
    {
        task* tk = new task;
        tk->_name += "pthread";
        tk->_name += i + '0';
        pthread_create(&(tk->_PT), nullptr, my_pthread, (void*)tk);
        arr.push_back(tk);
        // usleep(1000);
    }

    task* tk = new task;
    tk->_name += "pthread sign";
    pthread_create(&(tk->_PT), nullptr, mysign, (void*)tk);
    arr.push_back(tk);

    sleep(1);

    while(1)
    {
        pthread_mutex_lock(&MT);

        while(num > 0)
        {
            pthread_cond_wait(&m_cd, &MT);
        }

        num = 100;
        cout << "补票完成" << endl;
        sleep(1);
        pthread_cond_broadcast(&CD);
        pthread_mutex_unlock(&MT);
    }

    return 0;
}